from django.http import HttpResponse
from django.shortcuts import render, redirect
from django.urls import reverse
from Django040501.settings import *
# 导入用于分页的模块
from django.core.paginator import Paginator,EmptyPage,PageNotAnInteger

from . import models
from .classes import select

# Create your views here.

select_model = select.select()

def index(request):
    select_model.get_all()
    select_model.get_books()
    print('得到的书籍列表是:{}'.format(select_model.books_list))
    # 实现分页
    paginater = Paginator(select_model.books_list,PRE_PAGE_NUMBER)
    # 得到当前数据的页数
    page = request.GET.get('page')
    # 获取每页的数据
    try:
        current_page_books = paginater.page(page)
    except PageNotAnInteger:
        current_page_books = paginater.page(1)
    except EmptyPage:
        current_page_books = paginater.page(paginater.num_pages)
    for books in current_page_books:
        books['img'] = '../static/img/icon/' + str(books['bookid']) + '.jpg'
        author = models.Author.objects.filter(authorid=books['bookauthor_id']).values() #返回的是结果集，要用[0]取值
        books['author'] = author[0]['authorname']
        books['tip'] = ['热销书籍','这是真的好看，卧槽！']
    return render(request,'index.html',context={'select_item':select_model.select_item,'selected':select_model.selected,'books_list':current_page_books})


def select_click(request):
    # 获得选择的选项
    name = request.GET.get('name')
    type = request.GET.get('type')
    select_model.get_selected(name,type)
    return redirect(reverse('index'))


def get_keyword(request):
    # 获得输入的关键字
    keyword = request.GET.get('keyword')
    print('得到的keyword是{}'.format(keyword))
    select_model.selected['keyword'] = keyword
    return redirect(reverse('index'))


def get_all(request):
    select_model.clear_selected()
    return redirect(reverse('index'))


def get_order_number(request):
    order = request.GET.get('order')
    if order == '1':
        select_model.selected['order'] = 1
    elif order == '2':
        select_model.selected['order'] = 2
    return redirect(reverse('index'))